from flask import g, redirect, render_template, jsonify, current_app, request, session

from info.models import Category, News
from . import profile_blue
from info import db, constants
from info.utils.commons import login_required
from info.utils.response_code import RET
from info.utils.image_storage import storage


@profile_blue.route('/info')
@login_required
def user_info():
    user = g.user
    if not user:
        return redirect('/')

    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)


@profile_blue.route('/base_info', methods=['GET', 'POST'])
@login_required
def base_info():
    """
    基本信息展示和修改
    1. 获取参数, nick_name, signature, gender
    2. 检查参数的完整性
    3. 检查性别必须是MAN/WOMAN
    4. 保存用户信息
    5. 提交数据

    :return:
    """
    user = g.user
    if request.method == 'GET':

        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    # 检查教案参数的完整性
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    session['nick_name'] = nick_name
    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@login_required
def save_avatar():
    user = g.user
    if request.method == 'GET':
        print(1)
        data = {
            'user': user.to_dict()
        }
        return render_template("news/user_pic_info.html", data=data)
    avatar = request.files.get('avatar')
    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        image_data = avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数类型错误')

    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='上传头像异常')
    user.avatar_url = image_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'avatar_url': avatar_url
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blue.route('/news_release', methods=['GET', 'POST'])
@login_required
def news_release():
    user = g.user
    if request.method == 'GET':
        try:
            category_list = Category.query.all()
        except Exception as e:
            current_app.logger.errno(e)
            return jsonify(errno=RET.DBERR, errmsg="查询数据失败")
        if not category_list:
            return jsonify(errno=RET.NODATA, errmsg="无新闻数据")
        categories = []
        for category in category_list:
            categories.append(category.to_dict())
        categories.pop(0)
        data = {
            'categories': categories
        }
        print(1)
        return render_template('news/user_news_release.html', data=data)
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    print(2)
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='读取图片数据失败')
    try:
        image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误')
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='上传图片异常')
    news = News()
    news.category_id = category_id
    news.user_id = user.id
    news.source = '个人发布'
    news.title = title
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.content = content
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg="OK")